package itypes

import (
	"server/game/model"
	"server/share/config"

	"github.com/hwcer/updater"
	"github.com/hwcer/updater/operator"
)

var Unit = NewItemsIType(config.ITypeUnit)
var UnitBase = NewItemsIType(config.ITypeUnitBase)

func init() {
	Unit.stacked = ITypeUNStacked
	Unit.SetAttach(unitCreator)
	Unit.SetListener(unitListener)

	UnitBase.SetListener(unitBaseListener)
}

func unitCreator(u *updater.Updater, item *model.Items) (any, error) {
	item.Value = 1
	item.Attach.Set(model.AttachUnitLv, int32(1))
	//item.Attach.Set(model.AttachUnitRlv, int32(1))
	item.Attach.Set(model.AttachUnitLv, int32(1))
	_, _ = item.Attach.Marshal(model.AttachUnitMood, &model.UnitMood{Val: 200, Time: u.Milli()})

	if c := config.Data.Unit[item.IID]; c != nil {
		item.Attach.Set(model.AttachUnitSlv, c.Rare)
	}

	if skillSets := config.Data.SkillSets[item.IID]; skillSets != nil {
		skill := make([]int32, len(skillSets.Skills))
		for i := 0; i < len(skillSets.Skills); i++ {
			skill[i] = 1
		}
		_, _ = item.Attach.Marshal(model.AttachUnitSkill, skill)
	}

	return item, nil
}

func unitListener(u *updater.Updater, op *operator.Operator) {
	if op.Type == operator.TypesNew || op.Type == operator.TypesAdd {
		coll := u.Collection(config.ITypeCollect)
		coll.Add(op.IID, int32(op.Value))
	}
}
func unitBaseListener(u *updater.Updater, op *operator.Operator) {
	if op.Type == operator.TypesNew || op.Type == operator.TypesAdd {
		coll := u.Collection(config.ITypeCollect)
		if ub := config.Data.UnitBase[op.IID]; ub != nil {
			coll.Add(ub.Id, int32(op.Value))
		}

	}
}
